package com.ruoyi.web.controller.rhtx;


import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dj.domain.ExcelTable;
import com.ruoyi.dj.domain.Rhtxdj;
import com.ruoyi.dj.domain.excel.Cspz;
import com.ruoyi.dj.domain.excel.DjExcel;
import com.ruoyi.dj.domain.vo.RhtxdjVo;
import com.ruoyi.dj.service.IExcelTableService;
import com.ruoyi.dj.service.IRhtxdjService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 融合通信点检Controller
 *
 * @author ruoyi
 * @date 2024-04-24
 */
@RestController
@RequestMapping("/rhtx/dj")
public class RhtxdjController extends BaseController {
    @Autowired
    private IRhtxdjService rhtxdjService;
    @Autowired
    private IExcelTableService excelTableService;

    /**
     * 查询融合通信点检列表
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:rhtxdj:list')")
    @GetMapping("/list")
    public TableDataInfo list(RhtxdjVo rhtxdjVo) {
        startPage();
        List<Rhtxdj> rhtxdjs = rhtxdjService.selectRhtxdjList(rhtxdjVo);
        return getDataTable(rhtxdjs);
    }

    public static Boolean checkDateRange(Date startTime, Date endTime) throws ParseException {
        boolean a = true;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date cutoffDate = formatter.parse("2024-11-18");

        Calendar startCal = Calendar.getInstance();
        startCal.setTime(startTime);
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endTime);
        Calendar cutoffCal = Calendar.getInstance();
        cutoffCal.setTime(cutoffDate);

        while (!startCal.after(endCal)) {
            if (startCal.before(cutoffCal)) {
                a = false;
            }
            startCal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return a;
    }

    /**
     * 导出融合通信点检列表
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:rhtxdj:export')")
    @Log(title = "融合通信点检", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExcelTable excelTable) {
        ExcelTable excelTable1 = excelTableService.selectExcelTableByTableId(excelTable);
        Gson gson = new Gson();
        // 创建一个新的数组，用于存储name属性
        List<String> names = new ArrayList<>();
        if (!excelTable1.getSzm().equals("ll")) {
            names.add("cddw");
        }
        if (!excelTable1.getSzm().equals("rhtxdj")) {
            names.add("name");
        }
        if (!excelTable1.getSzm().equals("zhzhsspxcb")) {
            names.add("djwgsj");
        }
        if (!excelTable1.getSzm().equals("dxfhcjgdjb")) {
            names.add("djjgms");
        }

        RhtxdjVo rhtxdjVo = new RhtxdjVo();
        rhtxdjVo.setSzm(excelTable1.getSzm());
        rhtxdjVo.setTableId(excelTable1.getTableId());
        rhtxdjVo.setStartTime(excelTable.getStartTime());
        rhtxdjVo.setEndTime(excelTable.getEndTime());
        rhtxdjVo.setParentIds(excelTable.getParentIds());
        rhtxdjVo.setDeptIds(excelTable.getDeptIds());
        rhtxdjVo.setDictCodes(excelTable.getDictCodes());
        List<Rhtxdj> rhtxdjs = rhtxdjService.selectRhtxdjList(rhtxdjVo);
        List<Map<String, Object>> resultList = new ArrayList<>();

        for (SysDept dept : excelTable1.getDepts()) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("dept", dept);
            List<Rhtxdj> djList = rhtxdjs.stream().filter(i -> i.getDeptId().equals(dept.getDeptId())).collect(Collectors.toList());
            resultMap.put("dj", djList);
            resultList.add(resultMap);
        }
        ExcelUtil<DjExcel> djExcelExcelUtil = new ExcelUtil<>(DjExcel.class);
        List<DjExcel> djExcelList = new ArrayList<>();
        // 循环遍历 Rhtxdj 列表
        int serial = 1;
        for (int i = 0; i < resultList.size(); i++) {
            SysDept dept = (SysDept) resultList.get(i).get("dept");
            if (resultList.get(i).get("dj") != null) {
                List<Rhtxdj> dj = (List<Rhtxdj>) resultList.get(i).get("dj"); // 获取 Rhtxdj 列表
                for (int k = 0; k < dj.size(); k++) {
                    Rhtxdj rh = dj.get(k);
                    if (rh != null) {
                        if (excelTable1.getSzm().equals("ll")) {
                            // 将 JSON 字符串解析为 JsonElement
                            JsonElement jsonElement = JsonParser.parseString(rh.getJgms());
                            Boolean b = true;
                            try {
                                 b = checkDateRange(excelTable.getStartTime(), excelTable.getEndTime());
                            }catch (ParseException e) {
                                b=false;
                            }

                            if (jsonElement.isJsonArray()&& b) {
                                names.add("djwgsj");
                                names.add("djdictCode");
                                JsonArray jsonArray = jsonElement.getAsJsonArray();
                                // 遍历 JsonArray
                                for (JsonElement element : jsonArray) {
                                    if (element.isJsonObject()) {
                                        // 将每个元素转换为 JsonObject
                                        JsonObject jsonObject = element.getAsJsonObject();
                                        DjExcel djExcel = new DjExcel();
                                        djExcel.setSerial(serial++);//序号
                                        djExcel.setSjparent(dept.getParentName());//上级单位
                                        djExcel.setLrTime(new SimpleDateFormat("MM月dd日 HH:mm").format(rh.getLrTime()));//点检时间
                                        djExcel.setCddw(rh.getCddwV_dict_label());//抽点单位
                                        djExcel.setDept(dept.getDeptName());//被抽点单位
                                        djExcel.setDjlx(jsonObject.get("type").getAsString());
                                        djExcel.setDjnr(jsonObject.get("jgms").getAsString());
                                        djExcel.setDjys(jsonObject.get("time").getAsString());
                                        djExcel.setDjdb(jsonObject.get("dict_code").getAsString());
                                        djExcel.setDjmj(rh.getMj());
                                        djExcel.setJlr(rh.getUser().getNickName());//记录人
                                        djExcel.setDjremark(rh.getRemark());//备注
                                        System.out.println("djExcel: " + djExcel);
                                        // 将 DjExcel 对象添加到列表中
                                        djExcelList.add(djExcel);
                                    }
                                }
                            }else{
                                names.remove("djjgms");
                                names.add("djremark");
                                names.add("djlx");
                                names.add("djnr");
                                names.add("djys");
                                names.add("djdb");
                                names.add("djmj");
                                DjExcel djExcel = new DjExcel();
                                djExcel.setSerial(serial++);//序号
                                djExcel.setSjparent(dept.getParentName());//上级单位
                                djExcel.setDept(dept.getDeptName());//被抽点单位
                                djExcel.setLrTime(new SimpleDateFormat("MM月dd日").format(rh.getLrTime()));//点检时间
                                djExcel.setName(rh.getName());//被抽点人
                                if (rh.getSdd() != null) {
                                    djExcel.setDjdictCode(rh.getSdd().getDictLabel());//点检结果
                                }
                                djExcel.setCddw(rh.getCddwV_dict_label());//抽点单位
                                djExcel.setJlr(rh.getUser().getNickName());//记录人
                                djExcel.setDjjgms(rh.getJgms());//结果描述

                                if (rh.getWgsj() != null) {
                                    String[] wgsj = gson.fromJson(rh.getWgsj(), String[].class);
                                    if (wgsj[0] != null && wgsj[1] != null) {
                                        String time1 = wgsj[0].substring(11, 16);
                                        String time2 = wgsj[1].substring(11, 16);
                                        String result = time1 + "-" + time2;
                                        djExcel.setDjwgsj(result);//点检结果问题时间
                                    }
                                }
                                // 将 DjExcel 对象添加到列表中
                                djExcelList.add(djExcel);
                            }
                        }
                        else {
                            names.add("djremark");
                            names.add("djlx");
                            names.add("djnr");
                            names.add("djys");
                            names.add("djdb");
                            names.add("djmj");
                            DjExcel djExcel = new DjExcel();
                            djExcel.setSerial(serial++);//序号
                            djExcel.setSjparent(dept.getParentName());//上级单位
                            djExcel.setDept(dept.getDeptName());//被抽点单位
                            djExcel.setLrTime(new SimpleDateFormat("MM月dd日").format(rh.getLrTime()));//点检时间
                            djExcel.setName(rh.getName());//被抽点人
                            if (rh.getSdd() != null) {
                                djExcel.setDjdictCode(rh.getSdd().getDictLabel());//点检结果
                            }
                            djExcel.setCddw(rh.getCddwV_dict_label());//抽点单位
                            djExcel.setJlr(rh.getUser().getNickName());//记录人
                            djExcel.setDjjgms(rh.getJgms());//结果描述

                            if (rh.getWgsj() != null) {
                                String[] wgsj = gson.fromJson(rh.getWgsj(), String[].class);
                                if (wgsj[0] != null && wgsj[1] != null) {
                                    String time1 = wgsj[0].substring(11, 16);
                                    String time2 = wgsj[1].substring(11, 16);
                                    String result = time1 + "-" + time2;
                                    djExcel.setDjwgsj(result);//点检结果问题时间
                                }
                            }
                            // 将 DjExcel 对象添加到列表中
                            djExcelList.add(djExcel);
                        }
                    }
                }
            }
        }
        String[] name = names.toArray(new String[0]);
        djExcelExcelUtil.hideColumn(name);
        djExcelExcelUtil.exportExcel(response, djExcelList, excelTable1.getTableName());
    }



    /**
     * 获取融合通信点检详细信息
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:rhtxdj:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(rhtxdjService.selectRhtxdjById(id));
    }

    /**
     * 新增融合通信点检
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:rhtxdj:add')")
    @Log(title = "融合通信点检", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Rhtxdj rhtxdj) {
        rhtxdj.setCreateBy(getUsername());
        return toAjax(rhtxdjService.insertRhtxdj(rhtxdj));
    }

    /**
     * 修改融合通信点检
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:rhtxdj:edit')")
    @Log(title = "融合通信点检", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Rhtxdj rhtxdj) {
        rhtxdj.setUpdateBy(getUsername());
        return toAjax(rhtxdjService.updateRhtxdj(rhtxdj));
    }

    /**
     * 删除融合通信点检
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:rhtxdj:remove')")
    @Log(title = "融合通信点检", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id) {
        return toAjax(rhtxdjService.deleteRhtxdjById(id));
    }
}